from flask import Blueprint, request
from flask_login import login_required

from apps.a_common.error import get_param, InvalidParamError
from apps.a_common.response import success_response, error_response
from apps.search.helper import SEARCH_MAP

search_blueprint = Blueprint('search', __name__)


@search_blueprint.route('/search/')
@login_required
def _search():
    """
    搜索接口
    ---
    tags:
      - search
    parameters:
      - name: content_id
        in : query
        type: integer
        required: true
        description: 资源的id，1是搜user，2是搜permission
      - name: query
        in : query
        type: string
        required: false
        description: 搜索的关键词
    """
    params = request.args or request.form or request.get_json() or {}
    resource_id = get_param(params, 'resource_id', int)
    if resource_id not in SEARCH_MAP:
        return error_response(InvalidParamError(fields='不支持的搜索对象'))

    filter_, serializer = SEARCH_MAP[resource_id]
    return success_response(serializer(i) for i in filter_())
